/* 文章类别路由
 * @Author: Leil 
 * @Date: 2018-08-24 00:34:20 
 * @Last Modified by: Leil
 * @Last Modified time: 2018-09-06 17:16:03
 */
const categoryService = require('../service/categoryService')
const checkLogin = require('../middleware/check').checkLogin

module.exports = function (app) {

    app.all('/category', checkLogin)

    app.all('/category/:categoryId', checkLogin)

    // app.all('/categories', checkLogin)

    // 添加、更新文章分类信息
    app.post('/category', function (req, res) {
        const id = req.fields.id
        const title = req.fields.title
        const sort = req.fields.sort
        // console.log(req.fields)
        if (id) {
            categoryService.updateCategoryById(id, {
                title: title,
                sort: parseInt(sort)
            }).then(result => {
                return res.send(result)
            })
        } else {
            categoryService.addOneCategory({
                title: title,
                sort: parseInt(sort)
            }).then(result => {
                // console.log(result)
                return res.send(result)
            })
        }
    })

    // 获取所有分类信息
    app.get('/api/categories', async function (req, res) {
        console.log("categories....................")
        let data
        await categoryService
            .getAllCategories()
            .then(categories => {
                // console.log(categories)
                data = categories
            })
            .catch(error => {
                console.log(error)
            })
        return res.send(data)
    })

    // 删除某条分类信息
    app.delete('/category', function (req, res) {
        // console.log(req.fields.categoryId)
        let categoryId = req.fields.categoryId
        categoryService
            .delCategoryById(categoryId)
            .then(result => {
                return res.send(result)
            })
    })

    // 根据id获取某条分类信息
    app.get('/category/:categoryId', function (req, res) {
        let categoryId = req.params.categoryId
        // console.log(categoryId)
        categoryService
            .getCategoryById(categoryId)
            .then(category => {
                return res.send(category)
            })
    })
}